package uteis;

public class PoliticaFormularioParametro {

	// ///////////////////////////////////////////////////////////////
	// Valida CPF e CNPJ //
	// ///////////////////////////////////////////////////////////////

	public static boolean isValid(String cpfOrCnpj) {

		if (cpfOrCnpj == null)
			return false;
		String n = cpfOrCnpj.replaceAll("[^0-9]*", "");
		boolean isCnpj = n.length() == 14;
		boolean isCpf = n.length() == 11;
		if (!isCpf && !isCnpj)
			return false;
		int i;
		int j; // just count
		int digit; // A number digit
		int coeficient; // A coeficient
		int sum; // The sum of (Digit * Coeficient)
		int[] foundDv = { 0, 0 }; // The found Dv1 and Dv2
		int dv1 = Integer.parseInt(String.valueOf(n.charAt(n.length() - 2)));
		int dv2 = Integer.parseInt(String.valueOf(n.charAt(n.length() - 1)));
		for (j = 0; j < 2; j++) {
			sum = 0;
			coeficient = 2;
			for (i = n.length() - 3 + j; i >= 0; i--) {
				digit = Integer.parseInt(String.valueOf(n.charAt(i)));
				sum += digit * coeficient;
				coeficient++;
				if (coeficient > 9 && isCnpj)
					coeficient = 2;
			}
			foundDv[j] = 11 - sum % 11;
			if (foundDv[j] >= 10)
				foundDv[j] = 0;
		}
		return dv1 == foundDv[0] && dv2 == foundDv[1];
	}

}
